package system

import (
	"WchimeGinSystem/models"
	"WchimeGinSystem/storage"
	"WchimeGinSystem/utils"
	"WchimeGinSystem/utils/errmsg"
	jwtauth "WchimeGinSystem/utils/jwtAuth"

	"github.com/gin-gonic/gin"
)

type UserinfoRes struct {
	ID        int    `json:"id"`        //用户ID
	Username  string `json:"username"`  // 用户名
	Nickname  string `json:"nickname"`  // 昵称
	Avatar    string `json:"avatar"`    // 头像
	Mobile    string `json:"mobile"`    //手机号
	CreatedAt string `json:"createdAt"` //创建时间
}

// Userinfo
// @Summary 用户信息
// @Description 用户信息
// @Tags 用户信息
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Success 200 {object} UserinfoRes "返回"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /userinfo [get]
func Userinfo(c *gin.Context) {
	cursor_user, _ := c.Get("user")
	claims, ok := cursor_user.(*jwtauth.MyClaims)
	if !ok {
		utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_BASE, "")
		return
	}
	user_id := claims.UserId

	// fmt.Println(user_id)

	user := get_user_instance(int(user_id))

	res := UserinfoRes{
		ID:        user.Id,
		Username:  user.Username,
		Nickname:  user.Nickname,
		Mobile:    user.Mobile,
		Avatar:    user.Avatar,
		CreatedAt: user.CreatedAt.Format("2006-01-02 15:04:05"),
	}

	utils.RespContext(c).SuccessResp(res)

}

func get_user_instance(user_id int) models.User {
	var user models.User
	_ = models.DB.Where("id = ?", user_id).First(&user)
	return user
}

// Userinfo
// @Summary 用户修改头像
// @Description 用户修改头像
// @Tags 用户信息
// @Accept multipart/form-data
// @Param avatar formData file true "头像"
// @Produce json
// @Security ApiKeyAuth
// @Success 200 {object} UserinfoRes "返回"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /update_avatar [post]
func UpdateAvatar(c *gin.Context) {
	cursor_user, _ := c.Get("user")
	claims, ok := cursor_user.(*jwtauth.MyClaims)
	if !ok {
		utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_BASE, "")
		return
	}
	user_id := claims.UserId
	user := get_user_instance(int(user_id))

	avatar, err := c.FormFile("avatar")
	if err != nil {
		utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_BASE, "")
		return
	}
	avatar_byte, err := avatar.Open()
	if err != nil {
		utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_BASE, "")
		return
	}
	defer avatar_byte.Close()

	img_path, err := storage.UploadFile(avatar_byte, avatar.Filename, "user/avatar", "png")
	if err != nil {
		utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_BASE, "")
		return
	}
	user.Avatar = img_path
	models.DB.Save(&user)
	ava_url, _ := storage.GetFileURL(user.Avatar, nil)
	res := UserinfoRes{
		ID:        user.Id,
		Username:  user.Username,
		Mobile:    user.Mobile,
		Avatar:    ava_url,
		CreatedAt: user.CreatedAt.Format("2006-01-02 15:04:05"),
	}

	utils.RespContext(c).SuccessResp(res)

}

type ModifyPwdReq struct {
	Password  string `json:"password" binding:"required"`  // 原密码
	Password1 string `json:"password1" binding:"required"` // 新密码
	Password2 string `json:"password2" binding:"required"` // 确认密码
}

// Userinfo
// @Summary 用户修改密码
// @Description 用户修改密码
// @Tags 用户信息
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param req body ModifyPwdReq true "入参"
// @Success 200 {object} UserinfoRes "返回"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /update_pwd [post]
func UserModifyPWD(c *gin.Context) {
	cursor_user, _ := c.Get("user")
	claims, ok := cursor_user.(*jwtauth.MyClaims)
	if !ok {
		utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_BASE, "")
		return
	}
	user_id := claims.UserId

	var body ModifyPwdReq
	if err := c.ShouldBindJSON(&body); err != nil {
		utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_PARAMS_VALID, "")
		return
	}

	// fmt.Println(user_id)

	if (body.Password1 == "") || (body.Password1 != body.Password2) {

		utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_DOUBLE_PWD, "")
		return
	}

	user := get_user_instance(int(user_id))

	err := utils.CheckPassword(user.Password, body.Password)
	if err != nil {
		utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_MODIFYPWD_ERR, "")
		return
	}
	hash_pwd, err1 := utils.HashPassword(body.Password1)
	if err1 != nil {
		utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_BASE, "")
		return
	}
	user.Password = hash_pwd
	models.DB.Save(&user)

	res := UserinfoRes{
		ID:        user.Id,
		Username:  user.Username,
		Nickname:  user.Nickname,
		Mobile:    user.Mobile,
		Avatar:    user.Avatar,
		CreatedAt: user.CreatedAt.Format("2006-01-02 15:04:05"),
	}

	utils.RespContext(c).SuccessResp(res)

}

type UpdateUserinfoReq struct {
	Nickname string `json:"nickname"` // 昵称
	Mobile   string `json:"mobile"`   // 电话
}

// Userinfo
// @Summary 修改用户信息
// @Description 修改用户信息
// @Tags 用户信息
// @Accept json
// @Produce json
// @Security ApiKeyAuth
// @Param req body UpdateUserinfoReq true "入参"
// @Success 200 {object} UserinfoRes "返回"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /userinfo [put]
func UpdateUserinfo(c *gin.Context) {
	cursor_user, _ := c.Get("user")
	claims, ok := cursor_user.(*jwtauth.MyClaims)
	if !ok {
		utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_BASE, "")
		return
	}
	user_id := claims.UserId

	// fmt.Println(user_id)

	user := get_user_instance(int(user_id))

	var body UpdateUserinfoReq
	if err := c.ShouldBindJSON(&body); err != nil {
		utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_PARAMS_VALID, "")
		return
	}

	if body.Nickname != "" {
		user.Nickname = body.Nickname
	}

	if body.Mobile != "" {
		user.Mobile = body.Mobile
	}
	models.DB.Save(&user)

	res := UserinfoRes{
		ID:        user.Id,
		Username:  user.Username,
		Nickname:  user.Nickname,
		Mobile:    user.Mobile,
		Avatar:    user.Avatar,
		CreatedAt: user.CreatedAt.Format("2006-01-02 15:04:05"),
	}

	utils.RespContext(c).SuccessResp(res)

}
